package com.xxadmin.usercenter.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxadmin.common.constant.Iconstant;
import com.xxadmin.common.dto.PageInfoDTO;
import com.xxadmin.common.exception.BusinessException;
import com.xxadmin.common.util.clone.CopyUtils;
import com.xxadmin.common.util.page.PageUtils;
import com.xxadmin.usercenter.dao.ChannelDetailDao;
import com.xxadmin.usercenter.domain.ChannelDetail;
import com.xxadmin.usercenter.dto.ChannelDetailDTO;
import com.xxadmin.usercenter.dto.ChannelDetailQueryDTO;
import com.xxadmin.usercenter.service.ChannelDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 渠道接口实现类
 *
 * @author:chenming
 * @date:2018/8/30
 */
@Service
public class ChannelDetailServiceImpl implements ChannelDetailService {

    @Autowired
    private ChannelDetailDao channelDetailDao;

    @Override
    public PageInfoDTO<ChannelDetailDTO> listChannelDetail(ChannelDetailQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPageNum(),queryDTO.getPageSize());

        Page<ChannelDetail> page = channelDetailDao.selectChannelDetailPage(queryDTO);

        return PageUtils.getPageInfoDTO(page,ChannelDetailDTO.class);
    }

    @Override
    public void addChannelDetail(ChannelDetailDTO channelDetail) {

        if(channelDetailDao.selectByCode(channelDetail.getChannelCode()) != null){
            throw new BusinessException("该渠道编码已经存在，请不要重复添加");
        }

        ChannelDetail detail = CopyUtils.copyBean(channelDetail,ChannelDetail.class);
        detail.setStatus(Iconstant.STATUS_ENABLED);
        detail.setCreateTime(new Date());

        channelDetailDao.insertSelective(detail);
    }

    @Override
    public ChannelDetailDTO getChannelDetailById(Integer id) {
        ChannelDetail detail =  channelDetailDao.selectByPrimaryKey(id);

        return CopyUtils.copyBean(detail,ChannelDetailDTO.class);
    }

    @Override
    public void updateChannelDetail(ChannelDetailDTO channelDetail) {

        ChannelDetail temp = channelDetailDao.selectByCode(channelDetail.getChannelCode());
        if(!temp.getId().equals(channelDetail.getId())){
            throw new BusinessException("该渠道编码已经存在，请更换渠道编码");
        }

        ChannelDetail detail = CopyUtils.copyBean(channelDetail,ChannelDetail.class);

        detail.setUpdateTime(new Date());

        channelDetailDao.updateByPrimaryKeySelective(detail);
    }
}
